<template>
  <div class="app-container Account">
    <div class="container-fluid">
      <el-row>
        <el-col class="Accountlft" :md="17">
          <!-- lft-bar-->
          <div class="filter-container" id="Event">
            <el-button type="text">

              <div class="block">
                <span class="demonstration">Financial Year
                </span>

                <el-select v-model="listQuery.year"  placeholder="选择财年">
                  <el-option v-for="(y,i) in FinancialYear" :key='i' :value='y.year' :label='y.name'>
                  </el-option>
                </el-select>
                <!-- <el-date-picker
                        v-model="listQuery.year"
                        type="year"
                        placeholder="选择年">
                      </el-date-picker> -->
              </div>
            </el-button>
            <!-- <button type="button" class="el-button el-button--success fr" v-if="userType.indexOf('ADMIN')>-1"><span>Export</span></button> -->
          </div>
          <el-table v-loading="listLoading" :data="list" element-loading-text="Loading" border fit
            highlight-current-row stripe>
            <el-table-column label="Mounth/Year" prop='activitiesName'>
              <template slot-scope="scope">
                {{ scope.row.muneMonth | dateFormat('my','/')  }}
              </template>
            </el-table-column>
            <el-table-column label="Coach Cut-off" min-width="120" prop='levelName' show-overflow-tooltip>
              <template slot-scope="scope">
                {{ scope.row.coachCutOffDate  | dateFormat('',' ') }}
              </template>
            </el-table-column>
            <el-table-column label="Close Month" min-width="120" prop='levelName' show-overflow-tooltip>
              <template slot-scope="scope">
                {{ scope.row.confirmDate | dateFormat('',' ')}}
              </template>
            </el-table-column>
            <el-table-column label="Autopay Date" min-width="120" prop='levelName' show-overflow-tooltip>
              <template slot-scope="scope">
                {{ scope.row.autopayDate | dateFormat('',' ') }}
              </template>
            </el-table-column>

          </el-table>
          <!-- left--bar-end -->
        </el-col>

        <el-col :md='{span:6,offset:1}' >
          <el-form ref="infoResport" :model="infoResport" :rules="rules.infoResport">
            <el-card class="Accountbox-card Resport_card">
              <div slot="header" class="clearfix t-center">
                <span> Account Reports</span>
              </div>
              <div class="text itemBox">
                <el-form-item class="marBtm cpB" prop="resportVal">
                  <div class="padBtm marBtm titleH">Report Type：</div>
                  <el-select style='width:90%;' v-model="infoResport.resportVal" :label='infoResport.resportVal.typeName' placeholder="Report Type">
                    <el-option :value="list.typeCode" :label="list.typeName" v-for="(list,i) in $store.state.app.RESPORT_TYPE"
                      :key="i"></el-option>
                  </el-select>
                </el-form-item>

                <el-form-item class=" cpB" prop="FinancialMy">
                  <div class="padBtm marBtm titleH">Month/Year：</div>
                  <el-select multiple :collapse-tags='false' style='width:90%;height:40px' v-model="infoResport.FinancialMy"
                    placeholder="Month/Year">
                    <el-option :value="list.value" :label="list.label" v-for="(list,i) in monyhYear" :key="i"></el-option>
                </el-select>
                </el-form-item>
                <div class="flex-box center">
                  <el-button type="success" @click="submitForm('infoResport')">
                    View
                    <!--  <router-link :to="{name:'Autoplay'}" tag='div'>
                         View
                       </router-link> -->
                  </el-button>
                  <el-button type="success" @click='submitForm("infoResport",exportFn)'>
                    Export
                    </el-button>
                </div>
              </div>
            </el-card>
          </el-form>
          <!-- Coach Cut-off -->

          <el-card class="Accountbox-card Coach_card">
            <div slot="header" class="clearfix t-center">
              <span> Coach Cut-off</span>
            </div>
            <div class="text itemBox">
              <!-- {{muneaAccount.month==CoachVal}} -->

              <div class="marBtm cpB posRea t-center">

                     <el-button type="text" :disabled="hasCoachCutOff" @click="visiablePicker('CoachEl')"
                      class="posAb clPad  el-date-editor el-input el-input--prefix el-input--suffix el-date-editor--month"
                    style="width: 90%;"

                    >
                    <input type="text" readonly="readonly" autocomplete="off" name=""
                     v-model='CoachValEl'
                     placeholder="Select Mounth/Year" class="el-input__inner"><span
                      class="el-input__prefix"><i class="el-input__icon el-icon-date"></i>
                      </span><span class="el-input__suffix"><span class="el-input__suffix-inner"><i class="el-input__icon"></i>
                      </span>
                      </span>
                     </el-button>
                <el-date-picker :disabled="hasCoachCutOff" style='width:90%;visibility: hidden;' v-model="CoachVal" type="month" ref='CoachEl'
                  format="MM/yyyy"
                  value-format="yyyy-MM" placeholder="Select Mounth/Year">
                </el-date-picker>
              </div>
              <div class="marBtm t-center">
                <el-button @click='closeCoachFn' :disabled="hasCoachCutOff"
                :type="hasCoachCutOff?'default':'warning'" >Coach Cut-off</el-button>
              </div>
            </div>
          </el-card>
    <!-- {{CoachVal}} -->
          <!-- Coach Cut-off -->
          <el-card class="Accountbox-card Only_card">
            <div slot="header" class="clearfix t-center">
              <span> Account Only</span>

            </div>
            <div class="text itemBox">
              <div class="marBtm cpB posRea t-center">
                 <div class="padBtm marBtm titleH">Close Month：</div>
                <el-button type="text" :disabled="hasCloseConfirmDate" @click="visiablePicker('OnlyEl')"
                                      class="posAb  clPad el-date-editor el-input el-input--prefix el-input--suffix el-date-editor--month"
                                    style="width: 90%;">
                                    <input type="text"  readonly="readonly" autocomplete="off" name=""
                                     v-model='OnlyValEl'
                                     placeholder="Select Mounth/Year" class="el-input__inner"><span
                                      class="el-input__prefix"><i class="el-input__icon el-icon-date"></i>
                                      </span><span class="el-input__suffix"><span class="el-input__suffix-inner"><i class="el-input__icon"></i>
                                      </span>
                                      </span>
                                     </el-button>
                <el-date-picker :disabled="hasCloseConfirmDate" ref='OnlyEl' style='width:90%; visibility: hidden;' v-model="OnlyVal" type="month"
                  format="MM/yyyy" value-format="yyyy-MM" placeholder="Select Mounth/Year">
                </el-date-picker>
              </div>
              <div class="marBtm t-center">
                <el-button :type="hasCloseConfirmDate?'default':'danger'" @click='closeMonthFn' :disabled="hasCloseConfirmDate">Confirm</el-button>
              </div>
            </div>

            <div class="text itemBox">
              <div class="marBtm cpB">
                <div class="padBtm marBtm titleH">Autopay Date：</div>
                <div class="posRea t-center">
                <el-button type="text" :disabled="hasCloseAutopayDate" @click="visiablePicker('AutopayEl')"
                                      class="posAb clPad el-date-editor el-input el-input--prefix el-input--suffix el-date-editor--month"
                                    style="width: 90%;">
                                    <input type="text" readonly="readonly" autocomplete="off" name=""
                                     v-model='AutopayValEl'
                                     placeholder="Select Mounth/Year" class="el-input__inner"><span
                                      class="el-input__prefix"><i class="el-input__icon el-icon-date"></i>
                                      </span><span class="el-input__suffix"><span class="el-input__suffix-inner"><i class="el-input__icon"></i> </span>
                                      </span>
                                     </el-button>
                <el-date-picker :disabled="hasCloseAutopayDate" ref='AutopayEl' style='width:90%; visibility: hidden;' v-model="AutopayVal" type="month"
                  format="MM/yyyy" value-format="yyyy-MM" placeholder="Select Autopay Date">
                </el-date-picker>
                </div>

                <el-date-picker class="marTop" :disabled="hasCloseAutopayDate" style='width:90%;'
                  v-model="autopayDate"

                  format="dd/MM/yyyy" value-format="yyyy-MM-dd"

                  type="date" placeholder="Select Autopay Date">
                </el-date-picker>
              </div>
              <div class="marBtm t-center">
                <el-button :type="hasCloseAutopayDate?'default':'danger'" @click='closeAutopayFn' :disabled="hasCloseAutopayDate">Confirm</el-button>
              </div>
            </div>
          </el-card>
          <!-- #endif -->
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
  import {
    queryMuneList,
    closeAutopay,
    closeCoach,
    closeMonth,
    queryAutopayList,
    queryYearList,
    getPdf,
    checkViewData
    /*,querySessionsList,queryAllocationList,querySessionsList*/
  } from '@/api/account.js'

   import {parseTime} from '@/utils/'
  import {
    getEventList
  } from '@/api/event'
  const FullYear = new Date().getFullYear()
  const monyhYear = []

  export default {
    filters: {
      statusFilter(status) {
        const statusMap = {
          published: 'success',
          draft: 'gray',
          deleted: 'danger'
        }
        return statusMap[status]
      }
    },
    data() {
      return {
        FinancialYear: [
        ],
        monyhYear,
        infoResport: {
          resportVal: '',
          FinancialMy: '',
        },
        FinancialVal: new Date(),
        rules: {
          infoResport: {
            resportVal: [{
              required: true,
              message: 'please put in resportVal'
            }],
            FinancialMy: [{
              required: true,
              message: 'please put in FinancialMy'
            }]
          }
        },
        CoachVal:parseTime(new Date(),'{y}-{m}'),
        CoachValEl: this.$dateFormat(new Date(),'my','/'),
        OnlyVal:parseTime(new Date(),'{y}-{m}'),
        OnlyValEl: this.$dateFormat(new Date(),'my','/'),
        AutopayVal:parseTime(new Date(),'{y}-{m}'),
        AutopayValEl: this.$dateFormat(new Date(),'my','/'),
        autopayDate:parseTime(new Date(),'{y}-{m}-{d}'),

        userType: this.$store.getters.userType,
        list: [],
        hasCoachCutOff: false,
        hasCloseConfirmDate: false,
        hasCloseAutopayDate: false,
        listLoading: true,
        muneaAccount: {
          confirmDate:'',
          autopayDate:'',
          coachCutOff:''
        },
        listQuery: {
          page: 1,
          size: 25,
          keyword: '',
          year: FullYear,
          total: 0,
          column: '',
          sorting: 0

        },
        link: '/event/addEdit'
      }
    },

    watch: {
      ['listQuery.year'](val) {
        this.getMonthList(val)
      },
      CoachVal(val) {
        this.CoachValEl= this.$dateFormat(val,'my','/')
      },
      OnlyVal(val){
        this.OnlyValEl= this.$dateFormat(val,'my','/')
      },
      AutopayVal(val){
        this.AutopayValEl= this.$dateFormat(val,'my','/')
      },
    },

    mounted() {
      queryYearList().then((yearRes)=>{
        this.FinancialYear =  yearRes.result
      }).catch()
      this.getMonthList()
    },
    created() {
      console.log("撒大神", this)
      //this.$store.dispatch("app/getType", 'RESPOT_TYPE')
      this.fetchData()
    },
    methods: {
      fetchData() {
        var that = this
        queryMuneList({
          year: this.listQuery.year
        }).then((res) => {
          let result = res.result
          let newListAlly = []
          that.monyhYear.map((mYlis,y,mYt)=>{
            let b={autopayDate:'-',autopayDate:'',cts:'-',id:'',muneMonth:mYlis.value,uby:'',uts:'-'}
            result.list.map((mlis,i,mitem)=>{
              //let listuneMonth =mlis.muneMonth.split('-')[1]
              if(mYlis.value !== mlis.muneMonth){
              }else{
                 b=mlis
                //newListAlly.push(mlis)
              }
            })
            newListAlly.push(b)
          })
          //debugger
          this.list = newListAlly
          this.muneaAccount =  result
          this.hasCoachCutOff = Boolean(result.coachCutOffDate)
          this.hasCloseConfirmDate  = !this.hasCoachCutOff || Boolean(result.confirmDate)
          this.hasCloseAutopayDate  = !this.hasCoachCutOff ||  Boolean(result.autopayDate)
          this.CoachVal = result.month
          this.OnlyVal = result.month
          this.AutopayVal = result.month

          this.autopayDate =result.autopayDate
         // this.listQuery.total = result.total ? response.result.total : this.listQuery.total

          this.listLoading = false
        }).catch((err) => {

        })
        //this.CoachValEl=
      },

      visiablePicker(CoachEl){
       let that = this.$refs[CoachEl]
         //that.showPicker()
      },
      closeCoachFn() {
        //debugger
        var that = this
        this.$confirm('Do you confirm cut-off? This process is irreversible.').then((res)=>{
           closeCoach().then((res) => {
            that.hasCoachCutOff = true
            this.hasCloseConfirmDate = false
            this.hasCloseAutopayDate = false
            this.fetchData()
           // this.$router.go()
           }).catch((err) => {})
        }).catch((err)=>{
        })
      },
      closeMonthFn() {
        closeMonth().then((res) => {

          if(res.status === 0){
             this.hasCloseConfirmDate  = true
             this.fetchData()
          }
          this.$message({type:res.status?'warning':"success",message:res.msg})

        }).catch((err) => {})
      },
      closeAutopayFn() {
        var date = this.autopayDate
        // debugger
        if(date){
          closeAutopay({date}).then((res) => {
            if(res.status === 0){
              this.hasCloseAutopayDate  = true
              this.fetchData()
            }
            this.$message({type:res.status?'warning':"success",message:res.msg})
          }).catch((err) => {})
        }else{
          this.$message.error({message:'请选择Autopay Date'})
        }
      },
      submitForm(formName,canbackFn) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            var m = this.infoResport.FinancialMy.join(',')
            checkViewData(m).then((res)=>{
              if(res.status === 0){
                if(canbackFn){
                  return canbackFn();
                }
                this[formName + 'Fn'](valid)
              }
            })
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      //View fn
      infoResportFn() {
      this.$router.push({
          name: this.infoResport.resportVal,
          query: {
            months: this.infoResport.FinancialMy
          }
        })
      },
      //Export fn
       exportFn(){
         var resportVal=this.infoResport.resportVal
         let barName = 'account/'
         var exports =''
         this.$store.state.app.RESPORT_TYPE.map(lis=>{

           return resportVal===lis.typeCode?exports =lis.exports:''
         })

         barName += exports
         let months = this.infoResport.FinancialMy.join(',') //months

         this.$store.dispatch('app/onExport',{barName,params:{months,token:this.muneaAccount.exportToken}})
       },
      getMonthList(val) {
        if (this.infoResport.FinancialMy) {
          this.infoResport.FinancialMy = ''

        }
           this.monyhYear = []
        for (var y = 4; y <= 15; y++) {
          let mtr = y >= 13 ? y-12 : y
          var dy = (Number(val ? val : this.listQuery.year) + (y >= 13 ? 1 : 0)) + '-' + (mtr < 10 ? '0' + mtr : mtr);
          var b = {
            label: this.$dateFormat(dy, 'my', '/'),
            value: dy
          }
        this.monyhYear.push(b)
        }
      }
    }
  }
</script>
<style lang="scss">
  body {
    .Account {
      .el-divider--horizontal {
        margin: 0 auto;
      }

      .el-select__tags {
        >span {
          display: block;
          width: 100%;
          overflow: hidden;
          white-space: nowrap;
          //text-overflow: ellipsis;
          height: 100%;
        }
      }

      @media screen and (max-width: 780px) {
        .Accountlft {
          margin-bottom: 10px;
        }
      }

      .cell {
        text-align: center;
      }

      &box-card {
        .titleH {
          text-align: left;
        }

        text-align: center;
        margin-bottom: 10px;

        .el-card__header {}
      }

      .el-table--border td,
      .el-table--border th,
      .el-table__body-wrapper .el-table--border.is-scrolling-left~.el-table__fixed {
        border: 0;
      }
    }

    button.el-button--success {
      min-width: 100px;
    }

  }
</style>
<style lang="scss" scoped>

</style>
